const Koa = require('koa');
const path = require('path');
const { sep } = path;
const env = require('./env');

const middlewareLoader = require('./loader/middleware');
const configLoader = require('./loader/config');
const controllerLoader = require('./loader/controller');
const serviceLoader = require('./loader/service');
const extendLoader = require('./loader/extend');
const routerSchemaLoader = require('./loader/router-schema');
const routerLoader = require('./loader/router');


module.exports = {
    /**
     * 启动项目
     * @params options 项目配置
     */
    start(options = {}) {
        // koa 实例
        const app = new Koa();

        // 应用配置
        app.options = options;

        // 基础路径
        app.baseDir = process.cwd();
        
        // 业务文件路径
        app.businessPath = path.resolve(app.baseDir, `.${sep}app`);
        
        // 初始化环境变量
        app.env = env()
        console.log(`-- [start] env: ${app.env.get()} --`);

        // 加载loader
        middlewareLoader(app);
        console.log(`-- [start] loader: middleware done --`);

        routerSchemaLoader(app);
        console.log(`-- [start] loader: routerSchema done --`);

        controllerLoader(app);
        console.log(`-- [start] loader: controller done --`);

        serviceLoader(app);
        console.log(`-- [start] loader: service done --`);

        configLoader(app);
        console.log(`-- [start] loader: config done --`);

        extendLoader(app);
        console.log(`-- [start] loader: extend done --`);


        // 注册全局中间件
        try {
            require(`${app.businessPath}${sep}middleware.js`)(app)
            console.log(`-- [strat] loader: global middleware done --`);
        } catch (e) {
            console.log(e);
            
            console.log(`[exception] there is no global middleware file`);

        }
        
        // 加载路由
        routerLoader(app);

        //  启动服务
        try {
            const port = process.env.PORT || 8080;
            const host = process.env.IP || '0.0.0.0'
            app.listen(port, host);
            console.log(`Server running on port: ${port}`);

        } catch (e) {
            console.log(e);
        }
        return app;
    }
}